#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "gs.h"
#include "tank.h"
#include "jiaojie.h"

static FILE* add_new_file(const char *filename)
{
    FILE* fp;
    /*
     * Check current directory filelist, if the list more than 1000 delete oldest
     */

    fp = fopen(filename, "a+");

    return fp;
}

/*
 * param mode: same as access
 */
static FILE* gs_jiaojie_get_fp(int mode)
{
    time_t now_t;
    struct tm* tm;
    FILE *fp;
    char filename[128];

    time(&now_t);
    tm = localtime(&now_t);

    /* Get current date as filename, it's format is code_alarm_yyyymmdd.txt */
    sprintf(filename, "./jiaojie/%s_jiaojie_%4d%02d%02d.txt", 
            g_gs.code, tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);

    /* Check file exist in ./alarm directory 
     * if exist, open and return it, otherwize, add new file
     */
    if (access(filename, mode) == 0) {
        if (mode == R_OK)
            fp = fopen(filename, "r");
        else if (mode == W_OK)
            fp = fopen(filename, "a");
    }
    else {
        fp = add_new_file(filename);
    }

    return fp;
}


void gs_jiaojie_save(void)
{
    int i;
    GS_TANK *tank;
    time_t now_t;
    struct tm* tm;
    FILE *fp;
    fp = gs_jiaojie_get_fp(W_OK);
    
    time(&now_t);
    tm = localtime(&now_t);

    for (i=0;i<g_gs.tanks_nr;i++) {
        tank = &g_gs.tanks[i];

        fprintf(fp, "%s\t" // Code
                "%d\t" // Tank ID
                "%04d%02d%02d\t" // Date
                "%02d%02d%02d\t" // Time
                "%.1f\t" // Oil
                "%.1f\t" // Water
                "%.1f\t", // Temp
                g_gs.code,
                tank->tank_id,
                tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
                tm->tm_hour, tm->tm_min, tm->tm_sec,
                tank->oil,
                tank->water,
                tank->temp);
    }
    fclose (fp);
}

int gs_jiaojie_ftp(void)
{
    /* Get new file from alarm index file */

    /* Send file to ftp server */

    return 0;
}

int gs_jiaojie_init(void)
{
    mkdir("jiaojie", 00777);

    return 0;
}
